define('uploadFile', ['config', 'jquery'], function(config, $){
	return {
		uploadImgFiles:function(files,finalCallback){
	var responseUrls=[];//存储返回的url
	function uploadFirstInQueue() {
		var fileToUpload=files[0];
		var slashIndex = fileToUpload.type.indexOf("/");
		var suffix = fileToUpload.type.substring(slashIndex + 1);
		getUploadUrl(uploadImg, suffix, fileToUpload.type);

	};
	function getUploadUrl(callback, suffix, type) {
		console.log(suffix, type);
		$.ajax({
			url: "msq/api/image-url",
			type: "POST",
			data: {
				suffix: suffix,
				contentType: type
			},
			success: function(d) {
				callback(d.url, type);
			}
		});
	}

	function uploadImg(url, fileType) {
		var reader = new FileReader();
		// console.log(fileType);
		// console.log(imgFile);
		reader.onload = function(e) {
			$.ajax({
				url: url,
				type: "PUT",
				processData: false,
				headers: {
					"Content-Type": files[0].type,
				},
				contentType: files[0].type,
				data: e.target.result,
				success: function(d) {
					files.shift();//从任务队列移除已经完成的文件
					responseUrls.push(url.substring(0,url.indexOf("?")))
					if(files.length>0){//未完成
						uploadFirstInQueue();
					}else{
						//全部完成
						finalCallback(responseUrls);
						console.log("成功上传",responseUrls);
					}

				},
				error:function(){
					alert("上传错误");
					//再次尝试上传
				}
			});
		};
		reader.readAsArrayBuffer(files[0]);
	}

	uploadFirstInQueue();
	},
	uploadVideoFiles:function uploadVideoFiles(files,finalCallback){
	var responseUrls=[];//存储返回的url
	function uploadFirstInQueue() {
		var fileToUpload=files[0];
		var slashIndex = fileToUpload.type.indexOf("/");
		var suffix = fileToUpload.type.substring(slashIndex + 1);
		getUploadUrl(uploadVideo, suffix, fileToUpload.type);

	};
	function getUploadUrl(callback, suffix, type) {
		console.log(suffix, type);
		$.ajax({
			url: "msq/api/video-url",
			type: "POST",
			data: {
				suffix: suffix,
				contentType: type
			},
			success: function(d) {
				callback(d.url, type);
			}
		});
	}

	function uploadVideo(url, fileType) {
		var reader = new FileReader();
		// console.log(fileType);
		// console.log(imgFile);
		reader.onload = function(e) {
			$.ajax({
				url: url,
				type: "PUT",
				processData: false,
				headers: {
					"Content-Type": files[0].type,
				},
				contentType: files[0].type,
				data: e.target.result,
				success: function(d) {
					files.shift();//从任务队列移除已经完成的文件
					responseUrls.push(url.substring(0,url.indexOf("?")))
					if(files.length>0){//未完成
						uploadFirstInQueue();
					}else{
						//全部完成
						 finalCallback(responseUrls);
						console.log("成功上传视频",responseUrls);
					}

				},
				error:function(){
					alert("上传错误");
					//再次尝试上传
				}
			});
		};
		reader.readAsArrayBuffer(files[0]);
	}

	uploadFirstInQueue();
	}
	};
});

